import copy
import P0080_FIRSTVT_LASTVT as P0080

#构造算符优先关系表
def GetPrecedenceTable(grammar):
    FIRSTVT = P0080.FIRSTVT(grammar)
    LASTVT = P0080.LASTVT(grammar)

    PrecTableLowerThan = {}  # 算符优先关系表小于
    PrecTableHigherThan = {}  # 算符优先关系表大于
    PrecTableEqual = {}  # 算符优先关系表大于
    for terminal in grammar["terminals"]:
        PrecTableLowerThan[terminal] = set()
        PrecTableHigherThan[terminal] = set()
        PrecTableEqual[terminal] = set()

    for production in grammar["productions"]:
        left, right = production[0], production[1] 
        cnt = len(right)
        for i in range(cnt-1):
            if (right[i] in grammar["terminals"]) and (right[i + 1] in grammar["non_terminals"]): #aP形式，a<FIRSTVT[P]
                for vt in FIRSTVT[right[i+1]]:
                    PrecTableLowerThan[right[i]].update(vt)
            if (right[i] in grammar["non_terminals"]) and (right[i + 1] in grammar["terminals"]): #Pb形式，LASTVT[P]>b
                for vt in LASTVT[right[i]]:
                    PrecTableHigherThan[vt].update(right[i+1])
            if (i < cnt-2) and (right[i] in grammar["terminals"]) and (right[i + 1] in grammar["non_terminals"]) and (right[i+2] in grammar["terminals"]):  # aPb形式，a=b
                PrecTableEqual[right[i]].add(right[i+2])
                PrecTableEqual[right[i+2]].add(right[i])
       
    return PrecTableLowerThan,PrecTableHigherThan,PrecTableEqual

if __name__ == "__main__":        
    # print(f"FIRSTVT:\n{P0080.FIRSTVT(P0080.grammar3)}")
    # print(f"LASTVT:\n{P0080.LASTVT(P0080.grammar3)}")
    lower,higher,equal = GetPrecedenceTable(P0080.grammar3) 
    print("PrecTableLowerThan:")
    for low in lower:
        print(f"{low}:{lower[low]}")
    print("PrecTableHigherThan:")
    for high in higher:
        print(f"{high}:{higher[high]}")
    print("PrecTableEqual:")
    for eq in equal:
        print(f"{eq}:{equal[eq]}")

    # print(f"PrecTableLowerThan:\n{l}")
    # print(f"PrecTableHigherThan:\n{h}")